/*

    // 需要添加到一下配置到 .../res/values/attrs.xml
    <!-- 适用于 自定义 ***.widget.roundangle 圆角控件 -->
    <declare-styleable name="roundView">
        <attr name="radius" format="dimension"/>
    </declare-styleable>

*/
package com.assembly.videolist.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import com.assembly.videolist.R;


/** 圆角图片控件 */
public class RoundImageView extends AppCompatImageView {

    private int radius; // 半径，单位像素
    private RectF rectF;
    private Paint zonePaint;
    private Paint maskPaint;

    /** 设置半径 【radius = 半径；单位PX】 */
    public void setRadius(int radius) {
        setRadius(radius, true);
    }

    /** 设置半径 【radius = 半径；单位PX】【isInvalidate = 是否刷新View】 */
    public void setRadius(int radius, boolean isInvalidate) {
        this.radius = radius;
        this.rectF = null;
        this.zonePaint = null;
        this.maskPaint = null;
        if (isInvalidate)
            invalidate();
    }

    public RoundImageView(Context context, int radius) {
        super(context);
        this.radius = radius;
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /** 初始化样式参数 */
    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TasksCompletedView);
        this.radius = 0;
        typedArray.recycle();
    }

    @Override
    public void draw(Canvas canvas) {
        if (rectF == null || zonePaint == null || maskPaint == null) {
            rectF = new RectF();
            zonePaint = new Paint();
            maskPaint = new Paint();

            rectF.set(0, 0, getWidth(), getHeight());
            zonePaint.setAntiAlias(true);
            zonePaint.setColor(Color.WHITE);
            maskPaint.setAntiAlias(true);
            maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        }

        canvas.saveLayer(rectF, zonePaint, Canvas.ALL_SAVE_FLAG);
        canvas.drawRoundRect(rectF, radius, radius, zonePaint);
        canvas.saveLayer(rectF, maskPaint, Canvas.ALL_SAVE_FLAG);
        super.draw(canvas);
    }
}
